#! /bin/sh -
#
# Deploy static cross-compilers for easy distribution
#
# Copyright (c) 2016-2021 Matias Fonzo, <selk@dragora.org>.
# Copyright (c) 2022 DustDFG, <dfgdust@gmail.com>.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Exit immediately on any error
set -e

PROGRAM="${0##*/}"

# Override locale settings
LC_ALL=C
LANGUAGE=C
export LC_ALL LANGUAGE

umask 022

# Get physical working directory (absolute path)
CWD="$(CDPATH='' cd -P -- "$(dirname -- "$0")" && pwd -P)" || exit $?

### Functions

usage()
{
    printf '%s' \
"Usage: $PROGRAM [OPTIONS] [TARGET]...
Deploy static cross-compilers for easy distribution.

Where TARGET is any target found at the targets/ directory.
If no target name is passed, all available targets will be built.

Options:
  -j          Parallel jobs for the compiler [${jobs}]
  -h          Display this help and exit

Some influential environment variables:
  TMPDIR      Temporary directory for sources [${TMPDIR}]

Available targets from ${CWD}/targets ...

"
for name in "${CWD}/targets"/*
do
    sed -e '2q;d' "$name"
done
unset -v name
echo ""
}

warn()
{
    printf '%s\n' "$@" 1>&2
}

### Default values

jobs=1
output="${CWD}/OUTPUT.${PROGRAM}"
TMPDIR="${TMPDIR:=${output}/sources}"

export TMPDIR

### Parse options

while getopts :hj: name
do
    case $name in
    h)
        usage
        exit 0
        ;;
    j)
        jobs="$OPTARG"
        ;;
    :)
        warn "Option '-${OPTARG}' requires an argument"
        usage
        exit 1
        ;;
    \?)
        warn "Illegal option -- '-${OPTARG}'"
        usage
        exit 1
        ;;
    esac
done
shift $(( OPTIND - 1 ))
unset -f usage


# Compose tag for tarball names using yearNumber+monthName+dayNumber
tarname="darkcrusade_$(date +%Y%b%d)"

# Prepare to start the cross compiler process in the phase 1

phase_one="${output}/phase1-native-$(uname -m)-$(date +%Y-%m-%d.%H%M%S)-$$"

echo "${PROGRAM}: Creating native cross compiler on $phase_one ..."
"${CWD}"/bootstrap -j${jobs} -s0 -o "$phase_one"

# Now will start the preparatives to use the recent native cross compiler

echo "${PROGRAM}: Using (existing) compiler from $phase_one ..."

# Set flags according to the generated compiler
for BTCC in "${phase_one}"/cross/*/bin/*-gcc
do
    if test -x "$BTCC"
    then
        BTCC="$BTCC"
        break
    fi
done
for BTCXX in "${phase_one}"/cross/*/bin/*-g++
do
    if test -x "$BTCXX"
    then
        BTCXX="$BTCXX"
        break
    fi
done

# Set and compose flags to be used as CC/CXX

BTCC="$BTCC -static -Wl,-Bstatic -static-libgcc"
BTCXX="$BTCXX -static -Wl,-Bstatic -static-libgcc"

IS_DARKCRUSADE=IS_DARKCRUSADE

export BTCC BTCXX IS_DARKCRUSADE

# Loop for create the targets, phase 2
for target in "${CWD}"/targets/${@:-*}
do
    target="${target##*/}"

    phase_two="${output}/phase2-${target}-$(date +%Y-%m-%d.%H%M%S)-$$"

    logfile="${output}/${tarname}-${target}.log"

    # Build target against native compiler, logging its output

    echo "${PROGRAM}: Making target: $target ..."
    rm -f "${output}/bootstrapfailed"

    {
        "${CWD}"/bootstrap -j${jobs} -s0 -a "$target" -o "$phase_two" || touch "${output}/bootstrapfailed"
    } 2>&1 | tee "$logfile"

    if test -f "${output}/bootstrapfailed"
    then
        echo "${PROGRAM}: An error occurred while processing the target: $target" 1>&2
        echo "  Please check the log file $logfile" 1>&2
        exit 99;
    fi

    # Provide log file, tarball and checkum

    lzip -9 "$logfile" &

    (
        cd -- "$phase_two" && \
        tarlz --solid -9 -cv cross/ \
         -f "${output}/${tarname}-${target}.tar.lz"
    )
    (
        cd -- "$output" && \
        sha256sum "${tarname}-${target}.tar.lz" \
         > "${tarname}-${target}.tar.lz.sha256"
    )
done

